package com.hdphone.zljutils.impl;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.core.content.FileProvider;

import com.hdphone.zljutils.ZljUtils;
import com.hdphone.zljutils.inter.IActivityUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * @date: 2021/6/2
 * @email： yzandlj@163.com
 * @author： yangzhi
 * @describe:
 */
public class ActivityUtilImpl implements IActivityUtil {
    // 日志标识
    private final String TAG = "ActivityUtil";


    /**
     * 获取当前程序包名
     *
     * @return
     */
    @Override
    public String getPackageName() {
        String pkgName = null;
        PackageInfo info = null;
        try {
            info = ZljUtils.getApp().getPackageManager().getPackageInfo(ZljUtils.getApp().getPackageName(), PackageManager.GET_CONFIGURATIONS);
        } catch (PackageManager.NameNotFoundException e) {
            ZljUtils.LOG().e(TAG, "getPackageName error" + e.getMessage(), e);
        }
        if (info != null) {
            pkgName = info.packageName;
        }
        if (TextUtils.isEmpty(pkgName)) {
            pkgName = ZljUtils.getApp().getPackageName();
        }
        return pkgName;
    }

    /**
     * 获取当前程序版本号
     *
     * @return
     */
    @Override
    public int getVersionCode() {
        PackageManager pm = ZljUtils.getApp().getPackageManager();
        int versionCode = 0;
        try {
            PackageInfo info = pm.getPackageInfo(ZljUtils.getApp().getPackageName(), PackageManager.GET_CONFIGURATIONS);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            ZljUtils.LOG().e(TAG, "getVersionCode error" + e.getMessage(), e);
        }
        return versionCode;
    }

    /**
     * 获取当前程序版本名称
     *
     * @return
     */
    @Override
    public String getVersionName() {
        PackageManager pm = ZljUtils.getApp().getPackageManager();
        String versionName = "1.0.0";
        try {
            PackageInfo info = pm.getPackageInfo(ZljUtils.getApp().getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            if (info != null) {
                versionName = info.versionName;
            }
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (PackageManager.NameNotFoundException e) {
            ZljUtils.LOG().e(TAG, "getVersionName error", e);
        }
        return versionName;
    }

    /**
     * 获取Application Meta数据
     *
     * @return
     */
    @Override
    public String getApplicationMetaData(String key) {
        if (TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ZljUtils.getApp().getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ZljUtils.getApp().getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultData;
    }

    /**
     * 获取Activity Meta数据
     *
     * @return
     */
    @Override
    public Object getActivityMetaData(Class<?> clazz, String key) {
        try {
            ComponentName cn = new ComponentName(ZljUtils.getApp(), clazz);
            ActivityInfo info = ZljUtils.getApp().getPackageManager().getActivityInfo(cn, PackageManager.GET_META_DATA);
            return info.metaData.get(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 当前activity 是不是在顶部
     *
     * @return activityName  Activity的全称（包括包名)
     */
    @Override
    public boolean isTopCurrentActivity(String activityName) {
        ActivityManager am = (ActivityManager) ZljUtils.getApp()
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (!ZljUtils.BEAN().isEmpty(runningTasks)) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            ComponentName topActivity = taskInfo.topActivity;
            if (topActivity != null) {
                String topActivityName = topActivity.getClassName();
                if (TextUtils.equals(activityName, topActivityName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取Service Meta数据
     *
     * @return
     */
    @Override
    public Object getServiceMetaData(Class<?> clazz, String key) {
        ComponentName cn = new ComponentName(ZljUtils.getApp(), clazz);
        try {
            ServiceInfo info = ZljUtils.getApp().getPackageManager().getServiceInfo(cn, PackageManager.GET_META_DATA);
            return info.metaData.get(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取Receiver Meta数据
     *
     * @return
     */
    @Override
    public Object getReceiverMetaData(Class<?> clazz, String key) {
        ComponentName cn = new ComponentName(ZljUtils.getApp(), clazz);
        try {
            ActivityInfo info = ZljUtils.getApp().getPackageManager().getReceiverInfo(cn, PackageManager.GET_META_DATA);
            return info.metaData.get(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 隐藏键盘
     *
     * @param activity
     */
    @Override
    public void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(ZljUtils.getApp().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
    }

    /**
     * 获取手机名
     *
     * @param
     * @return
     */
    @Override
    public String getPhoneName() {
        return android.os.Build.PRODUCT;
    }

    @Override
    public String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }

    /**
     * 判断应用是否是前台运行
     *
     * @return
     */
    @Override
    public boolean isForeground() {
        try {
            ActivityManager manager = (ActivityManager) ZljUtils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName topName = manager.getRunningTasks(1).get(0).topActivity;
            String currentPackageName = topName.getPackageName();
            if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(ZljUtils.getApp().getPackageName())) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 判断应用是否是前台运行
     * 注：经测试发现，有时会出现判断失误，故目前使用isForeground。
     *
     * @return
     */
    @Override
    public boolean isForegroundV2() {
        ActivityManager activityManager = (ActivityManager) ZljUtils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(ZljUtils.getApp().getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        return true;
    }

    /**
     * 安装APK
     * <p>
     * 上下文
     *
     * @param filePath 文件路径
     */
    @Override
    public void installApk(String filePath) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(FileProvider.getUriForFile(ZljUtils.getApp(), "com.huodao.hdphone.fileprovider", new File(filePath)), "application/vnd.android.package-archive");
        ZljUtils.getApp().startActivity(intent);
    }

    /**
     * 拨号
     *
     * @param phoneNum
     */
    @Override
    public void dial(String phoneNum) {
        Intent dial = new Intent(Intent.ACTION_DIAL);
        dial.setData(Uri.parse("tel:" + phoneNum));
        ZljUtils.getApp().startActivity(dial);
    }

    /**
     * 通过类名启动Activity
     *
     * @param pClass
     */
    @Override
    public void openActivity(Activity activity, Class<?> pClass) {
        openActivity(activity, pClass, null);
    }

    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pClass
     * @param pBundle
     */
    @Override
    public void openActivity(Activity activity, Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(activity, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        ZljUtils.getApp().startActivity(intent);
    }

    /**
     * Created by lambo on 2018/4/21.
     * 判断服务是否 还在运行
     * servicername:服务的名称
     */
    @Override
    public boolean isRunning(String servicername) {
        ZljUtils.LOG().d(TAG, "isRunning servicername = " + servicername);
        ActivityManager am = (ActivityManager) ZljUtils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> infos = am.getRunningServices(100);
        for (ActivityManager.RunningServiceInfo info : infos) {
            String name = info.service.getClassName();
            if (servicername.equals(name)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public  boolean inMainProcess() {
        String mainProcessName = ZljUtils.getApp().getApplicationInfo().processName;
        String processName = getProcessName();
        return TextUtils.equals(mainProcessName, processName);
    }

    /**
     * 获取当前进程名
     *
     * @return 进程名
     */
    private String getProcessName() {
        BufferedReader reader = null;
        try {
            File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
            reader = new BufferedReader(new FileReader(file));
            return reader.readLine().trim();
        } catch (IOException e) {
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
